package com.fa.common.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Component
public class DingTalkRobotUtil {

    @Value("${dingtalk.robot.webhook}")
    private String webhook;

    @Value("${dingtalk.robot.keyword}")
    private String keyword;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 发送文本消息到钉钉群
     *
     * @param content 消息内容（必须包含关键词）
     * @return 推送结果（成功/失败原因）
     */
    public String sendTextMessage(String content) {
        try {
            // 构建钉钉消息体（文本类型）
            Map<String, Object> message = new HashMap<>();
            message.put("msgtype", "text");
            Map<String, String> text = new HashMap<>();
            text.put("content", "【" + keyword + "】：" + content); // 拼接关键词，避免被拦截
            message.put("text", text);

            // 发送POST请求
            String jsonMessage = JSON.toJSONString(message);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> entity = new HttpEntity<>(jsonMessage, headers);

            /**
             * 使用restTemplate发送POST请求
             * @param webhook 钉钉机器人Webhook地址
             * @param entity  包含消息体的HTTP实体(即发到服务器的数据)
             * @return 包含响应体的 ResponseEntity
             */
            ResponseEntity<String> response = restTemplate.postForEntity(webhook, entity, String.class);
            // 解析响应结果
            if (response.getStatusCode().is2xxSuccessful()) {
                String result = response.getBody();
                JSONObject jsonResult = JSON.parseObject(result);
                if (jsonResult.getInteger("errcode") == 0) {
                    return "钉钉推送成功";
                } else {
                    return "钉钉推送失败：" + jsonResult.getString("errmsg");
                }
            } else {
                return "钉钉接口调用失败，状态码：" + response.getStatusCodeValue();
            }
        } catch (Exception e) {
            return "钉钉推送异常：" + e.getMessage();
        }
    }

    public String sendTextMessageAtPeople(String content, String[] atMobiles) {
        try {
            // 构建钉钉消息体（文本类型）
            Map<String, Object> message = new HashMap<>();
            message.put("msgtype", "text");
            Map<String, String> text = new HashMap<>();
            text.put("content", "【" + keyword + "】：" + content); // 拼接关键词，避免被拦截
            message.put("text", text);
            //  @指定人
            Map<String, Object> at = new HashMap<>();
            at.put("atMobiles", atMobiles);
            at.put("isAtAll", false);
            message.put("at", at);
            // 发送POST请求
            String jsonMessage = JSON.toJSONString(message);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> entity = new HttpEntity<>(jsonMessage, headers);
            ResponseEntity<String> response = restTemplate.postForEntity(webhook, entity, String.class);

            // 解析响应结果
            if (response.getStatusCode().is2xxSuccessful()) {
                String result = response.getBody();
                JSONObject jsonResult = JSON.parseObject(result);
                if (jsonResult.getInteger("errcode") == 0) {
                    return "钉钉推送成功";
                } else {
                    return "钉钉推送失败：" + jsonResult.getString("errmsg");
                }
            } else {
                return "钉钉接口调用失败，状态码：" + response.getStatusCodeValue();
            }
        } catch (Exception e) {
            return "钉钉推送异常：" + e.getMessage();
        }
    }

    /**
     * 发送消息给所有人
     *
     * @param content 消息内容（必须包含关键词）
     * @return 推送结果（成功/失败原因）
     */
    public String sendTextMessageAtAll(String content) {
        try {
            // 构建钉钉消息体（文本类型）
            Map<String, Object> message = new HashMap<>();
            message.put("msgtype", "text");
            Map<String, String> text = new HashMap<>();
            text.put("content", "【" + keyword + "】：" + content); // 拼接关键词，避免被拦截
            message.put("text", text);
            //  @所有人
            Map<String, Object> at = new HashMap<>();
            at.put("atMobiles", new String[]{});
            at.put("isAtAll", true);
            message.put("at", at);
            // 发送POST请求
            String jsonMessage = JSON.toJSONString(message);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> entity = new HttpEntity<>(jsonMessage, headers);
            ResponseEntity<String> response = restTemplate.postForEntity(webhook, entity, String.class);
            // 解析响应结果
            if (response.getStatusCode().is2xxSuccessful()) {
                String result = response.getBody();
                JSONObject jsonResult = JSON.parseObject(result);
                if (jsonResult.getInteger("errcode") == 0) {
                    return "钉钉推送成功";
                } else {
                    return "钉钉推送失败：" + jsonResult.getString("errmsg");
                }
            } else {
                return "钉钉接口调用失败，状态码：" + response.getStatusCodeValue();
            }
        } catch (Exception e) {
            return "钉钉推送异常：" + e.getMessage();
        }

    }
}

